package com.bishe.serivce.Impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.bishe.dao.OrgDao;
import com.bishe.pojo.Org;
import com.bishe.serivce.IOrgService;
import com.bishe.utils.EcoBootException;
import com.bishe.utils.SqlQueryUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 部门接口实现
 * @date 2022/03/20 42:08:37
 */
@Service
public class OrgServiceImpl implements IOrgService {
    @Autowired
    private OrgDao orgDao;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<Org> findAll() {
        return orgDao.findAll();
    }

    @Override
    public Org findById(String id) {
        return orgDao.findById(id);
    }

    @Override
    public void deleteById(String id) {
        orgDao.deleteById(id);
    }

    @Override
    public void updateById(Org org) {
        orgDao.updateById(org);
    }

    @Override
    public void save(Org org) {
        orgDao.save(org);
    }

    @Override
    public void addOrUpdate(Org org) {
        if (StrUtil.isEmpty(org.getId())){
            throw new EcoBootException("id为空");
        }
        //保存
        if (orgDao.findById(org.getId()) == null){
            org.setId(org.getId());
            save(org);
            return;
        }
        //修改
        updateById(org);
    }

    @Override
    public List<Org> list() {
        List<Org> list = new SqlQueryUtils<Org>(Org.class, jdbcTemplate).eq(Org::getPid, "0").getList();

        setOrg(list);

        return list;
    }

    @Override
    public void delete(String id) {
        Org byId = findById(id);
        if (byId!=null){
            byId.setPid("delete");
            updateById(byId);
        }
    }

    /**
     * 获取子部门
     * @param list
     */
    private void setOrg(List<Org> list){
        for (Org org : list) {
            //获取子部门列表
            List<Org> orgs = getOrgs(org);
            //子部门不为空
            if (CollUtil.isNotEmpty(orgs)){
                org.setOrgs(orgs);
                setOrg(orgs);
            }
        }
    }

    /**
     * 获取子部门列表
     * @param org
     * @return
     */
   private List<Org> getOrgs(Org org){
       return new SqlQueryUtils<Org>(Org.class, jdbcTemplate).eq(Org::getPid, org.getId()).getList();
   }


}